<template>
  <div class="user-container">
  <el-card shadow="never">
    <div class="toolbar">
      <el-input v-model="search" placeholder="搜索姓名/昵称/手机号/邮箱" style="width: 200px;" @keyup.enter="fetchList" clearable />
      <el-select v-model="gender" placeholder="全部性别" clearable style="width: 140px; margin-left: 10px;">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
      <el-select v-model="userLevel" placeholder="全部等级" clearable style="width: 140px; margin-left: 10px;">
        <el-option label="普通用户" :value="1" />
        <el-option label="VIP用户" :value="2" />
        <el-option label="高级VIP" :value="3" />
      </el-select>
      <el-button type="primary" @click="handleAdd" style="margin-left: 10px;">新增用户</el-button>
    </div>
    
    <el-table :data="tableData" border stripe :header-cell-style="{ background: '#faf5fe', color: '#6f21c8' }"  height="calc(100vh - 240px)" v-loading="loading">
      <el-table-column prop="userId" label="ID" width="60" align="center" />
      <el-table-column prop="avatarUrl" label="头像" width="80" align="center">
        <template #default="{ row }">
          <el-avatar 
            v-if="row.avatarUrl" 
            :src="fileBaseUrl() + row.avatarUrl" 
            :size="50"
            style="border-radius: 50%;"
          />
          <el-avatar v-else :size="50" style="background-color: #f0f0f0;">
            <el-icon><User /></el-icon>
          </el-avatar>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="name" label="姓名" width="100" /> -->
      <el-table-column prop="nickname" label="昵称" width="100" />
      <el-table-column prop="gender" label="性别" width="60" align="center" />
      <el-table-column prop="phoneNumber" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
      <el-table-column prop="userLevel" label="等级" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getLevelTagType(row.userLevel)">
            {{ getLevelText(row.userLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="points" label="积分" width="80" align="center" />
      <!-- <el-table-column prop="role" label="角色" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
            {{ row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="registrationTime" label="注册时间" min-width="140" />
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link @click="handleLevel(row)">等级</el-button>
          <!-- <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button> -->
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchList"
        @current-change="fetchList"
      />
    </div>
    
    <UserEditDialog
      v-model:visible="editDialogVisible"
      :user="currentUser"
      :is-edit="isEdit"
      @submit="handleSubmit"
    />
    
    <UserLevelDialog
      v-model:visible="levelDialogVisible"
      :user="currentUser"
      @submit="handleLevelSubmit"
    />
  </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import UserEditDialog from './UserEditDialog.vue'
import UserLevelDialog from './UserLevelDialog.vue'
import { getUserList, addUser, updateUser, deleteUser} from '@/apis/admin/user'
import { fileBaseUrl } from '@/apis/files'

const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const search = ref('')
const gender = ref('')
const userLevel = ref('')

const editDialogVisible = ref(false)
const levelDialogVisible = ref(false)
const isEdit = ref(false)
const currentUser = ref({})

// 获取等级标签类型
const getLevelTagType = (level) => {
  switch (level) {
    case 1: return 'info'
    case 2: return 'warning'
    case 3: return 'danger'
    default: return 'info'
  }
}

// 获取等级文本
const getLevelText = (level) => {
  switch (level) {
    case 1: return '普通用户'
    case 2: return 'VIP用户'
    case 3: return '高级VIP'
    default: return '普通用户'
  }
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await getUserList({
      current: currentPage.value,
      size: pageSize.value,
      search: search.value,
      gender: gender.value,
      userLevel: userLevel.value
    })
    if (res.code === '0') {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (e) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 监听搜索和筛选条件变化
watch([search, gender, userLevel], () => {
  currentPage.value = 1
  fetchList()
})

const handleAdd = () => {
  isEdit.value = false
  currentUser.value = {}
  editDialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentUser.value = { ...row }
  editDialogVisible.value = true
}

const handleLevel = (row) => {
  currentUser.value = { ...row }
  levelDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await deleteUser(row.userId)
      if (res.code === '0') {
        ElMessage.success('删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
}

// const handleResetPassword = (row) => {
//   ElMessageBox.confirm(`确定要重置 ${row.name} 的密码吗？`, '提示', { type: 'warning' })
//     .then(async () => {
//       const res = await resetUserPassword(row.userId)
//       if (res.code === '0') {
//         ElMessage.success('密码重置成功')
//       } else {
//         ElMessage.error(res.msg || '密码重置失败')
//       }
//     })
// }

const handleSubmit = async (form) => {
  loading.value = true
  try {
    const api = isEdit.value ? updateUser : addUser
    const res = await api(form)
    if (res.code === '0') {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      editDialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

const handleLevelSubmit = async (form) => {
  loading.value = true
  try {
    const res = await updateUser(form)
    if (res.code === '0') {
      ElMessage.success('等级更新成功')
      levelDialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '等级更新失败')
    }
  } catch (e) {
    ElMessage.error('等级更新失败')
  } finally {
    loading.value = false
  }
}

// const handleLevelSubmit = async (form) => {
//   loading.value = true
//   try {
//     // 先更新等级
//     const levelRes = await updateUserLevel(form.userId, form.userLevel)
//     if (levelRes.code === '0') {
//       // 再更新积分
//       const pointsRes = await updateUserPoints(form.userId, form.points)
//       if (pointsRes.code === '0') {
//         ElMessage.success('等级和积分更新成功')
//         levelDialogVisible.value = false
//         fetchList()
//       } else {
//         ElMessage.error(pointsRes.msg || '积分更新失败')
//       }
//     } else {
//       ElMessage.error(levelRes.msg || '等级更新失败')
//     }
//   } catch (e) {
//     ElMessage.error('等级更新失败')
//   } finally {
//     loading.value = false
//   }
// }

onMounted(fetchList)
</script>

<style scoped>
.user-container {
  padding: 20px;
}
.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>